#include "sys/dirent.h"
#include <string.h>
#include <errno.h>
#include <resource.h>
#include "Directory.h"
#include "File.h"
#include "FileDescriptor.h"
#include "Process.h"

extern int errno;
extern u32int _process;

extern "C" DIR *opendir (const char *name)
{
//   char *new_name = new(true) char[strlen(name)+1];
//   strcpy(new_name, name);
//   u32int fd = callResource(_process, Process_IF::createFileDescriptor, new_name, 0, 0);
//   if (!fd)
//   {
//       errno = ENOENT;
//       return NULL;
//   }
//   u32int file = callResource(fd, FileDescriptor_IF::getFile);
//   u32int fd_num = callResource(fd, FileDescriptor_IF::getId);
//   if (callResource(file, File_IF::identify) != eFileType_Directory)
//   {
//     callResource(_process, Process_IF::destroyFileDescriptor, fd_num);
//     errno = ENOTDIR;
//     return NULL;
//   }
//   DIR *dir = new DIR;
//   dir->fd = (int)fd_num;
//   dir->index = 0;
//   dir->dir = file;
//   return dir;
  errno = ENOSYS;
  return 0;
}

extern "C" struct dirent *readdir (DIR *dir)
{
  u32int f = callResource(dir->dir, Directory_IF::getEntryN, dir->index);
  if (!f)
  {
    return NULL;
  }
  strcpy(dir->ent.d_name, (const char*)callResource(f, File_IF::getName));
  dir->ent.d_ino = 1;
  dir->index ++;
  return &dir->ent;
}

extern "C" void rewinddir (DIR *dir)
{
  dir->index = 0;
}

extern "C" int closedir (DIR *dir)
{
  callResource(_process, Process_IF::destroyFileDescriptor, dir->fd);
  delete dir;
  return 0;
}

extern "C" void seekdir(DIR *dir, long n)
{
  dir->index = n;
}

extern "C" long telldir(DIR *dir)
{
  return (int)dir->index;
}
